<?php

namespace app\admin\model\cms;

use app\admin\model\UserGroup;
use app\admin\model\UserRule;
use think\Db;
use think\Exception;
use think\Model;
use traits\model\SoftDelete;

//应用 栏目表
class Channels extends Model
{

    use SoftDelete;

    // 表名
    protected $name = 'channels';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'creat_time';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'delete_time_text',
        'status_text',
    ];

    
   public function getStatusList()
    {
//        return ['0' => __('State 0'), '1' => __('State 1'), '2' => __('State 2')];
        return ['1'=>__('Allsee'),'2'=>__('Membersee'),'3'=>__('Partsee'), '0'=>__('Hidden')];
//        return ['addtabs' => __('Addtabs'), 'dialog' => __('Dialog'), 'ajax' => __('Ajax'), 'blank' => __('Blank')];
    }


    public function getDeleteTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['delete_time']) ? $data['delete_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setDeleteTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }
    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    // 递归构建树形结构的数组
    public static function buildTree($data, $parentId) {

        //正序排列
        if ($parentId > 0){
            usort($data, function($a, $b) {
                return $a['list_order'] - $b['list_order'];
            });
        }
        $tree = [];
        foreach ($data as $item) {
            if ($item['parent_id'] == $parentId) {
                $item['children'] = self::buildTree($data, $item['id']);
                $tree[] = $item->toArray();
            }
        }
        return $tree;
    }

    //联动创建 栏目表数据+用户权限表数据
    public function cascadeAdd($parent_id,$correlation_id,$name,$description){
       $res = [
         'code'=>200,
         'msg'=>'创建成功',
       ];
        Db::startTrans();
        try {
            //在栏目表中创建2级分类数据
            $channel = Channels::create([
                'parent_id' => $parent_id,
                'correlation_id' => $correlation_id,//关联id
                'name' => $name,//分类名称
                'as_name' => $name,//分类别名
                'is_del' => 0,//是否删除0:否,1:是
                'is_sidebar' => 0,//是否显示在侧边栏|0=否,1=是
                'description' => $description,//分类描述
            ]);
            $channel_id = $channel->id;//2级分类的id
            $channels_top = Channels::where('id',$parent_id)->find();//查顶级分类
            //创建角色权限表数据
            $user_rule_top = UserRule::where('title',$channels_top['name'])->where('pid',1)->find();//查顶级分类数据
            if (!$user_rule_top){
                //没查到-创建顶级分类的权限
                $user_rule = UserRule::create([
                    'pid'=>1,//前台
                    'title'=>$channels_top['name'],
                    'remark'=>$channels_top['description'],
                    'ismenu'=>1,//是否菜单|1:是
                    'createtime'=>time(),
                    'status'=>'normal',
                    'column_id'=>$channels_top['id']
                ]);
                //创建2级分类数据
                UserRule::create([
                    'pid'=>$user_rule->id,//前台
                    'title'=>$name,
                    'remark'=>$description,
                    'ismenu'=>1,//是否菜单|1:是
                    'createtime'=>time(),
                    'status'=>'normal',
                    'column_id'=>$channel_id
                ]);

            }else{
                //查到了-创建2级分类
                UserRule::create([
                    'pid'=>$user_rule_top['id'],//父级分类的id
                    'title'=>$name,
                    'remark'=>$description,
                    'ismenu'=>1,//是否菜单|1:是
                    'createtime'=>time(),
                    'status'=>'normal',
                    'column_id'=>$channel_id
                ]);
            }
            Db::commit();
        }catch (Exception $exception){
            Db::rollback();
            $res['code'] = 500;
            $res['msg'] = $exception->getMessage();
        }

        return $res;
    }

    //联动编辑 栏目表数据+用户权限表数据
    public function cascadeEdit($parent_id,$correlation_id,$name,$description){
        $res = [
            'code'=>200,
            'msg'=>'编辑成功',
        ];
        Db::startTrans();
        try {
            $channel = Channels::where('parent_id',$parent_id)->where('correlation_id',$correlation_id)->find();//查分类表中的2级分类信息
            if ($channel){
                Channels::where('parent_id',$parent_id)->where('correlation_id',$correlation_id)->update([
                    'parent_id'=>$parent_id,
                    'correlation_id'=>$correlation_id,//关联id
                    'name'=>$name,//分类名称
                    'as_name'=>$channel['as_name'],//分类名称
                    'is_del'=>0,//是否删除0:否,1:是
                    'is_sidebar'=>$channel['is_sidebar'],//是否显示在侧边栏|0=否,1=是
                    'description'=>$description,//分类描述
                ]);

                $user_rule = UserRule::where('title',$channel['name'])->where('pid','>',1)->find();//查我要更新的数据是否存在
                if (!$user_rule){
                    //查当前栏目表的2级分类数据的顶级分类名称
                    $channels_top = Channels::where('id',$parent_id)->find();
                    $user_rule_top = UserRule::where('title',$channels_top['name'])->where('pid',1)->find();//查我要更新数据的顶级分类是否存在
                    if ($user_rule_top){
                        $pid = $user_rule_top['id'];
                    }else{
                        //先创建权限表的顶级分类
                        $user_rule_create = UserRule::create([
                            'pid'=>1,//前台
                            'title'=>$channels_top['name'],
                            'remark'=>$channels_top['description'],
                            'ismenu'=>1,//是否菜单|1:是
                            'createtime'=>time(),
                            'status'=>'normal',
                            'column_id'=>$channels_top['id']
                        ]);
                        $pid = $user_rule_create->id;
                    }
                    //创建权限表的2级分类
                    $user_rule = UserRule::create([
                        'pid'=>$pid,//前台
                        'title'=>$name,
                        'remark'=>$description,
                        'ismenu'=>1,//是否菜单|1:是
                        'createtime'=>time(),
                        'status'=>'normal',
                        'column_id'=>$channel['id']
                    ]);
                }else{
                    //查到了-创建2级分类
                    UserRule::where('id',$user_rule['id'])->update([
                        'title'=>$name,
                        'remark'=>$description,
                        'ismenu'=>1,//是否菜单|1:是
                        'column_id'=>$channel['id']
                    ]);
                }

            }else{
                //联动创建 栏目表数据+用户权限表数据
                $res = $this->cascadeAdd($parent_id,$correlation_id,$name,$description);
            }
            Db::commit();
        }catch (Exception $exception){
            Db::rollback();
            $res['code'] = 500;
            $res['msg'] = $exception->getMessage();
        }

        return $res;
    }

    //联动删除 栏目表数据+用户权限表数据+更新用户gropu表数据
    public function cascadeDelete($parent_id,$correlation_id){
        //删除栏目表数据
        $channels = Channels::where('parent_id',$parent_id)->where('correlation_id',$correlation_id)->find();
        if (!$channels){
            return ['code'=>200,'msg'=>'删除成功'];
        }
        Db::startTrans();
        try {
            //联动删除分类
            Channels::where('parent_id',$parent_id)->where('correlation_id',$correlation_id)->delete();
            //删除权限表数据
            UserRule::where('column_id',$channels['id'])->delete();
            //更新相关的用户group表的rules(权限表id)字段 精准查询rules字段总有指定值(100%匹配)的数据
            $user_group = UserGroup::whereRaw("FIND_IN_SET({$channels['id']}, rules)")->select();
            //循环更新用户权限
            foreach($user_group as $v){
                $v['rules'] .= ',146';
                $rules = explode(',',$v['rules']);
                $index = array_search($channels['id'], $rules);
                if ($index !== false) {
                    unset($rules[$index]);
                }
                $rules_str = implode(',',$rules);
                UserGroup::where('id',$v['id'])->update([
                    'rules'=>$rules_str
                ]);
            }
            Db::commit();
            return ['code'=>200,'msg'=>'删除成功'];
        }catch (Exception $exception){
            Db::rollback();
            return ['code'=>500,'msg'=>$exception->getMessage()];
        }


    }

    //一对多,自己关联自己
    public function getChannels(){
        return $this->hasMany(self::class, 'parent_id', 'id');
    }

}
